package com.rowline.admin.module.util.utils;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.util.List;
import java.util.UUID;

/**
 * ClassName:StringUtil
 * Created by 245167
 * on 2017/8/18  18:53
 * description:
 */
public class StringUtil {

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        return uuid;
    }

    /**
     * 对象toString()
     * @param obj
     * @return
     */
    public static String toString(Object obj) {

        if (null == obj) {
            return "";
        }
        if (obj instanceof String) {
            return String.valueOf(obj);
        }
        if (obj instanceof List) {
            return ToStringBuilder.reflectionToString(((List) obj).toArray(),
                    ToStringStyle.SHORT_PREFIX_STYLE);
        }

        if (obj instanceof Enum) {
            return ((Enum) obj).name();
        }
        return ToStringBuilder.reflectionToString(obj,
                ToStringStyle.SHORT_PREFIX_STYLE);
    }

    /**
     * 字符串截取
     * @param s
     * @param n
     * @param encodeName
     * @return
     */
    public static String truncate(String s, int n, String encodeName) {

        try {
            if (s == null || s.isEmpty()) {
                throw new NullPointerException(
                        "StringUtils: truncate(String s, int n), 参数s不能为空！");
            }
            if (n <= 0) {
                throw new ArrayIndexOutOfBoundsException(
                        "StringUtils: truncate(String s, int n), 参数n不能为负数!");
            }

            if (n > s.getBytes(encodeName).length) {
                n = s.getBytes(encodeName).length;
            }

            byte[] resultBytes = new byte[n];
            int j = 0;
            for (int i = 0; i < s.length(); i++) {
                byte[] bytes = String.valueOf(s.charAt(i)).getBytes(encodeName);
                if (bytes.length <= n - j) {
                    for (int k = 0; k < bytes.length; k++) {
                        resultBytes[j] = bytes[k];
                        j++;
                    }
                } else {
                    break;
                }
            }
            return new String(resultBytes, 0, j, encodeName);
        } catch (Exception ex) {
            return "";
        }
    }

}
